﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using WoChu.RfClient.Entity;
using WoChu.RfClient.Common;
using WoChu.CF.BaseFrame.Util;

namespace WoChu.RfClient.Duty
{
    public partial class FrmTakeStock : Form
    {
        public FrmTakeStock()
        {
            InitializeComponent();
        }

        private static Dictionary<string, GoodsInfo> _dictGoodsCode = null;
        public static Dictionary<string, GoodsInfo> dictGoodsCode
        {
            get
            {
                if (_dictGoodsCode == null) _dictGoodsCode = new Dictionary<string, GoodsInfo>();
                return _dictGoodsCode;
            }
        }

        private static Dictionary<string, string> _dictGoodsBarCode = null;
        public static Dictionary<string, string> dictGoodsBarCode
        {
            get
            {
                if (_dictGoodsBarCode == null) _dictGoodsBarCode = new Dictionary<string, string>();
                return _dictGoodsBarCode;
            }
        }

        private static Dictionary<string, List<TakeStockInfo>> _dictLocationCode = null;
        public static Dictionary<string, List<TakeStockInfo>> dictLocationCode
        {  
            get
            {
                if (_dictLocationCode == null) _dictLocationCode = new Dictionary<string, List<TakeStockInfo>>();
                return _dictLocationCode;
            }
        }

        private static List<TakeStockInfo> lstTakeStock = null;
        private static List<TakeStockInfo> _lstListStock = null;
        public static List<TakeStockInfo> lstListStock
        {
            get
            {
                if (_lstListStock == null) _lstListStock = new List<TakeStockInfo>();
                return _lstListStock;
            }
        }

        private void FrmTakeStock_Load(object sender, EventArgs e)
        { 
            List<GoodsInfo> _lstGoods = Duty.TakeStockUIRule.NewInstance.GetGoodsInfo(LoginBean.Instance.USERCODE);
            if (_lstGoods != null && _lstGoods.Count > 0)
            {
                foreach (var _goods in _lstGoods)
                {
                    if (!dictGoodsCode.ContainsKey(_goods.GOODSCODE))
                    {
                        dictGoodsCode.Add(_goods.GOODSCODE, _goods);
                    }
                    if (!dictGoodsBarCode.ContainsKey(_goods.BARCODE))
                    {
                        dictGoodsBarCode.Add(_goods.BARCODE, _goods.GOODSCODE);
                    }
                }
            }

            List<GoodsInfo> _lstLocations = Duty.TakeStockUIRule.NewInstance.GetLocationInfo(LoginBean.Instance.USERCODE);
            if (_lstLocations != null && _lstLocations.Count > 0)
            {
                foreach (var _location in _lstLocations)
                {
                    if (!dictLocationCode.ContainsKey(_location.LOCATIONCODE))
                    {
                        List<TakeStockInfo> _lstTakeStockInfo = new List<TakeStockInfo>();
                        TakeStockInfo _takeStockInfo = new TakeStockInfo();
                        _takeStockInfo.GOODSCODE = _location.GOODSCODE;
                        _takeStockInfo.GOODSID = _location.GOODSID;
                        _takeStockInfo.GOODSNAME = _location.GOODSNAME;
                        _takeStockInfo.LOCATIONCODE = _location.LOCATIONCODE;
                        _takeStockInfo.LOCATIONID = _location.LOCATIONID;
                        _takeStockInfo.UNITNAME = _location.UNITNAME;
                        _takeStockInfo.SNAPQTY = _location.SNAPQTY;
                        _takeStockInfo.QTY = 0;
                        _lstTakeStockInfo.Add(_takeStockInfo);

                        dictLocationCode.Add(_location.LOCATIONCODE, _lstTakeStockInfo);
                    }
                    else
                    {
                        TakeStockInfo _takeStockInfo = new TakeStockInfo();
                        _takeStockInfo.GOODSCODE = _location.GOODSCODE;
                        _takeStockInfo.GOODSID = _location.GOODSID;
                        _takeStockInfo.GOODSNAME = _location.GOODSNAME;
                        _takeStockInfo.LOCATIONCODE = _location.LOCATIONCODE;
                        _takeStockInfo.LOCATIONID = _location.LOCATIONID;
                        _takeStockInfo.UNITNAME = _location.UNITNAME;
                        _takeStockInfo.SNAPQTY = _location.SNAPQTY;
                        _takeStockInfo.QTY = 0;
                        dictLocationCode[_location.LOCATIONCODE].Add(_takeStockInfo);
                    }
                }
            }

            txtLocation.Focus();
        }
       
        //显示扫描行
        private void SelectionBright(string barcode)
        {
            //if (lstLocationGoods == null || lstLocationGoods.Count <= 0) return;
            ////设置已扫描的为加亮
            //List<LocationGoodsInfo> _LocationGoods = lstLocationGoods.FindAll(o => o.Selected);
            //foreach (var _item in _LocationGoods)
            //{
            //    this.dbGridOnShelves.Select(lstLocationGoods.IndexOf(_item));

            //    this.dbGridOnShelves.SelectionBackColor = Color.Green;
            //}

           
            if (string.IsNullOrEmpty(barcode)) return;
             int curIndex = lstTakeStock.FindIndex(x => x.GOODSCODE == barcode);
            dbGridTakeStock.Select(curIndex);
            this.dbGridTakeStock.SelectionForeColor = Color.Green; 

            //else if (barNo.Length == 6)
            //{
            //    List<LocationGoodsInfo> lstCellNos=lstLocationGoods.FindAll(o=>o.GOODSBATCHCODE==barNo);
            //    foreach(var item in lstCellNos)
            //    {
            //        this.dbGridOnShelves.Select(lstLocationGoods.IndexOf(item)); 
            //        this.dbGridOnShelves.SelectionBackColor = Color.Green; 
            //    }
            //}
            
        }
        
        //扫描排序
        private void Sort()
        {

            lstTakeStock.Sort((x, y) =>
            {
                return x.QTY.CompareTo(y.QTY);
            });
            this.dbGridTakeStock.Refresh();
        }

        private void txtLocation_GotFocus(object sender, EventArgs e)
        {
            txtLocation.Text = string.Empty;
            txtLocation.Focus();
            txtLocation.SelectAll();
        }

        //回车货位操作
        private void txtLocation_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode != Keys.Enter) return;

            try
            {
                string LtCode = txtLocation.Text.Trim();
                if (string.IsNullOrEmpty(LtCode) || !dictLocationCode.ContainsKey(LtCode))
                {
                    MessageBox.Show("请扫正确货位码！");
                    txtLocation.SelectAll();
                    return;
                }

                //获取当前货期的商品数据
                lstTakeStock = dictLocationCode[LtCode];

                this.takeStockSource.DataSource = null;
                this.takeStockSource.DataSource = lstTakeStock;
                this.dbGridTakeStock.DataSource = this.takeStockSource;
                this.dbGridTakeStock.Refresh();

                txtQty.Text = string.Empty;
                txtBarCode.Text = string.Empty;
                txtBarCode.Focus();
                txtBarCode.SelectAll();
            }
            catch (Exception ex)
            {
                txtLocation.SelectAll();
                WoChu.CF.BaseFrame.Util.MessageBoxEx.Show(ex);
            }
        }


        //商品批次条码回车操作
        private void txtBarCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode != Keys.Enter) return;

            try
            {

                if (lstTakeStock == null && lstTakeStock.Count <= 0)
                {
                    MessageBoxEx.Show("请先扫描货位条码");
                    txtLocation.Focus();
                    txtLocation.SelectAll();
                    return;
                }

                string _barCode = txtBarCode.Text.Trim();
                if (string.IsNullOrEmpty(_barCode))
                {
                    MessageBox.Show("请扫描条码！");
                    txtBarCode.Focus();
                    txtBarCode.SelectAll();
                    return;
                }

                string _Code = _barCode;
                if (_barCode.Length == 18) //处理商品
                {
                    //string strs0 = '0'.ToString();
                    //if(!_barCode.StartsWith(strs0))
                    _Code = _barCode.Substring(0, 10);
                    if (!dictGoodsCode.ContainsKey(_Code))
                    {
                        _Code = string.Empty;
                    }
                }
                else if (_barCode.Length == 13)
                {
                    if (dictGoodsBarCode.ContainsKey(_barCode))
                    {
                        _Code = dictGoodsBarCode[_barCode];
                    }
                    else
                    {
                        _Code = string.Empty;
                    }
                }
                else 
                {
                    if (!dictGoodsCode.ContainsKey(_Code)) 
                    {
                        _Code = string.Empty;
                    }
                }
                if (string.IsNullOrEmpty(_Code))
                {
                    MessageBox.Show("扫描条码错误！");
                    txtBarCode.Focus();
                    txtBarCode.SelectAll();
                    return;
                }

                Cursor.Current = Cursors.WaitCursor;

                TakeStockInfo curitem = lstTakeStock.Find(x => x.GOODSCODE == _Code);
                if (curitem == null)
                {
                    TakeStockInfo _item = new TakeStockInfo();
                    GoodsInfo _goods = dictGoodsCode[_Code];

                    _item.GOODSCODE = _goods.GOODSCODE;
                    _item.GOODSID = _goods.GOODSID;
                    _item.GOODSNAME = _goods.GOODSNAME;
                    _item.LOCATIONCODE = lstTakeStock[0].LOCATIONCODE;
                    _item.LOCATIONID = lstTakeStock[0].LOCATIONID;
                    _item.UNITNAME = _goods.UNITNAME;
                    _item.SNAPQTY = _goods.SNAPQTY;
                    _item.QTY = 0;

                    curitem = _item;
                    lstTakeStock.Add(curitem);
                }        

                this.takeStockSource.DataSource = null;
                this.takeStockSource.DataSource = lstTakeStock;
                this.dbGridTakeStock.DataSource = this.takeStockSource;
                this.dbGridTakeStock.Refresh();
                SelectionBright(curitem.GOODSCODE);              
                txtQty.Text = string.Empty;
                txtQty.Focus();

            }
            catch (Exception ex)
            {
                txtBarCode.Focus();
                txtBarCode.SelectAll();
                WoChu.CF.BaseFrame.Util.MessageBoxEx.Show(ex);
            }
            finally
            {  
                Cursor.Current = Cursors.Default;
            }
        }
        
        //回车数量操作
        private void txtQty_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode != Keys.Enter) return;

            string _txtQty = this.txtQty.Text.Trim();

            if (!string.IsNullOrEmpty(_txtQty))
            {
                decimal _Qty = 0;
                try
                {
                    _Qty = Convert.ToDecimal(_txtQty);
                }
                catch
                {
                    WoChu.CF.BaseFrame.Util.MessageBoxEx.Show("输入的数量不正确!");
                    this.txtQty.Text = string.Empty;
                    this.txtQty.Focus();
                    return;
                }

                int curIndex = dbGridTakeStock.CurrentRowIndex;
                if (curIndex < 0)
                {
                    MessageBox.Show("请选选择的数据行！");
                    return;
                }

                TakeStockInfo curItem = lstTakeStock[curIndex];
                curItem.QTY = _Qty;

                if (!lstListStock.Contains(curItem))     
                {
                    lstListStock.Add(curItem);
                    lstListStock.Contains(curItem);
                }

                this.takeStockSource.DataSource = null;
                this.takeStockSource.DataSource = lstTakeStock;
                this.dbGridTakeStock.DataSource = this.takeStockSource;
                this.dbGridTakeStock.Refresh();

                //设置已扫描的为加亮
                SelectionBright(curItem.GOODSCODE);

                this.lblQtySum.Text = lstTakeStock.Sum(o => o.QTY).ToString();
                this.txtQty.Text = string.Empty;
                this.txtBarCode.Text = string.Empty;
                this.txtLocation.Text = string.Empty;
                this.txtLocation.Focus();
            }
        }
        //关闭窗体
        private void FrmOnShelves_Closed(object sender, EventArgs e)
        {
            //System.Reflection.Assembly ass = System.Reflection.Assembly.Load("WoChu.RfClient.Login");
            //Type type = ass.GetType("WoChu.RfClient.Login.FrmMain");
            //Object o = Activator.CreateInstance(type);
            //System.Reflection.MethodInfo mi = type.GetMethod("Show"); 
            //mi.Invoke(o, null);
            if (lstTakeStock != null && lstTakeStock.Count > 0)
            {
                //if (MessageBoxEx.Question("退出将清空当前数据？") == DialogResult.Yes)
                //{
                //tMessageBox.Show("")
                    lstTakeStock.Clear();
                    lstListStock.Clear();
                    dictGoodsCode.Clear();
                    dictGoodsBarCode.Clear();
                    dictLocationCode.Clear();

                //}
            }
            this.Close();
            this.Dispose();
        }

        //关闭窗体提示
        private void FrmOnShelves_Closing(object sender, CancelEventArgs e)
        {
            if (MessageBoxEx.Question("将退出该窗体清空数据，确认是否退出？") == DialogResult.No)
                e.Cancel = true;
            
        }

        
        private void dbGridTakeStock_Click(object sender, EventArgs e)
        {
            int curIndex = dbGridTakeStock.CurrentRowIndex;
            if (curIndex < 0) return;

            TakeStockInfo curItem = lstTakeStock[curIndex];
            txtLocation.Text = curItem.LOCATIONCODE;
            txtBarCode.Text = curItem.GOODSCODE;
            SelectionBright(curItem.GOODSCODE); 
            txtQty.Text = string.Empty;
            txtQty.Focus();
            txtQty.SelectAll();
        }
        
        private void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor.Current = Cursors.WaitCursor;

                if (lstListStock != null && lstListStock.Count > 0)
                {
                    if (WoChu.CF.BaseFrame.Util.MessageBoxEx.Question("是否提交？") == DialogResult.No) return;

                    var re = Duty.TakeStockUIRule.NewInstance.InsertTakeStock(LoginBean.Instance.USERCODE, lstListStock);

                    if (re.Params)
                    {
                        //lstTakeStock.Clear();
                        lstListStock.Clear();
                        //dictGoodsCode.Clear();
                        //dictGoodsBarCode.Clear();
                        //dictLocationCode.Clear();
                        this.takeStockSource.DataSource = null;
                        this.dbGridTakeStock.DataSource = this.takeStockSource;
                        this.dbGridTakeStock.Refresh();

                        this.listStockSource.DataSource = null;
                        this.dbGridListStock.DataSource = this.listStockSource;
                        this.dbGridListStock.Refresh();

                        txtLocation.Text = string.Empty;
                        txtBarCode.Text = string.Empty;
                        txtQty.Text = string.Empty;
                        lblQtySum.Text = string.Empty;
                        lblCount.Text = string.Empty;
                        lblSum.Text = string.Empty;
                        tabControlTakeStock.SelectedIndex = 0;
                        txtLocation.Focus();
                        txtLocation.SelectAll();
                        MessageBox.Show("提交成功！");
                    }
                    else
                    {
                        MessageBox.Show(re.Message);
                        return;
                    }
                }
                else
                {
                    MessageBoxEx.Show("请扫描盘点数据再提交！");
                    return;
                }
            }
            catch (Exception ex)
            {
                WoChu.CF.BaseFrame.Util.MessageBoxEx.Show(ex);
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }
 
        private void tabControlTakeStock_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabControlTakeStock.TabPages[tabControlTakeStock.SelectedIndex].Name == tabListStock.Name)
            {
                if (lstListStock == null || lstListStock.Count <= 0) return;

                this.listStockSource.DataSource = null;
                this.listStockSource.DataSource = lstListStock;
                this.dbGridListStock.DataSource = this.listStockSource;
                this.dbGridListStock.Refresh();

                this.lblCount.Text = (from itme in lstListStock group itme by itme.LOCATIONCODE into g select new { LOCATIONCODE = g.Count() }).Count().ToString();
                this.lblSum.Text = lstListStock.Sum(o => o.QTY).ToString();
            }
        }

        private void dbGridListStock_DoubleClick(object sender, EventArgs e)
        {
            int curIndex = dbGridListStock.CurrentRowIndex;
            if (curIndex < 0) return;
            try
            {

                TakeStockInfo curItem = lstListStock[curIndex];

                string ltCode = curItem.LOCATIONCODE;
                string gbName = curItem.GOODSNAME;

                string Message = string.Format("货位:{0}, 名称:{1}, \n 是否删除该数据？", ltCode, gbName);
                if (MessageBoxEx.Question(Message) == DialogResult.Yes)
                {
                    lstListStock.Remove(curItem);
                    this.listStockSource.DataSource = null;
                    this.listStockSource.DataSource = lstListStock;
                    this.dbGridListStock.DataSource = this.listStockSource;
                    this.dbGridListStock.Refresh();
                }
            }
            catch (Exception ex)
            {
                TraceEx.Write(ex.Message);
                WoChu.CF.BaseFrame.Util.MessageBoxEx.Show("删除数据失败!");
            }
            finally
            {
                txtBarCode.Focus();
                txtBarCode.SelectAll();
            }

        }
        
    }
}